package org.smart4j.framework.helper;

import org.smart4j.framework.utils.ReflectionUtil;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Bean 操作类
 * @Description:
 * @Author: Administrator
 * @Date: 2017/8/14 0014 下午 9:18
 */
public class BeanHelper {

    /**
     * 存储所有的bean类与实体类之间的映射关系，线程安全
     */
    private static Map<Class<?>, Object> BEAN_MAP = new ConcurrentHashMap<>();

    static {
        Set<Class<?>> classSet = ClassHelper.getBeanClassSet();
        for (Class<?> clazz : classSet) {
            Object instance = ReflectionUtil.mewInstance(clazz);
            BEAN_MAP.put(clazz, instance);
        }
    }

    /**
     * 获取bean 映射map
     * @return
     */
    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    public static<T> T getBean(Class<T> clazz) {
        if (!BEAN_MAP.containsKey(clazz)) {
            throw new RuntimeException("can not get org.smart4j.framework.bean [" + clazz + " ]");
        }
        return (T) BEAN_MAP.get(clazz);
    }

    /**
     * 将目标与代理
     * @param cls
     * @param obj
     */
    public static void setBean(Class<?> cls, Object obj) {
        BEAN_MAP.put(cls, obj);
    }

}
